<?php
/**
 * 深度诊断"系统管理"菜单为什么不显示
 */

require __DIR__ . '/vendor/autoload.php';

// 初始化应用
$app = new think\App();
$app->initialize();

echo "=== 深度诊断系统管理菜单 ===\n\n";

// 1. 检查数据库中的菜单数据
echo "【1】数据库中的菜单数据\n";
$host = '113.44.136.17';
$port = 3306;
$database = 'qiandao';
$username = 'qiandao';
$password = 'NGbks3HWx5PhSxDX';

try {
    $pdo = new PDO("mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->query("
        SELECT id, pid, title, icon, node, url, sort, status 
        FROM system_menu 
        WHERE pid = 0 AND status = 1 
        ORDER BY sort DESC, id ASC
    ");
    $topMenus = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "一级菜单（按显示顺序）：\n";
    foreach ($topMenus as $menu) {
        echo sprintf("  %s (ID:%d, SORT:%d, URL:%s, ICON:%s)\n", 
            $menu['title'], 
            $menu['id'], 
            $menu['sort'],
            $menu['url'],
            $menu['icon'] ?: '(无)'
        );
        
        // 检查子菜单
        $stmt2 = $pdo->prepare("SELECT COUNT(*) FROM system_menu WHERE pid = ? AND status = 1");
        $stmt2->execute([$menu['id']]);
        $subCount = $stmt2->fetchColumn();
        echo "    子菜单数量: {$subCount}\n";
    }
    
} catch (PDOException $e) {
    echo "数据库错误: " . $e->getMessage() . "\n";
}

// 2. 模拟登录并获取菜单
echo "\n【2】模拟 admin 用户获取菜单\n";

// 清除所有缓存
try {
    \think\facade\Cache::clear();
    echo "  ✓ 已清除缓存\n";
} catch (\Exception $e) {
    echo "  清除缓存失败: " . $e->getMessage() . "\n";
}

// 模拟登录
$_SESSION = [];
$_SESSION['user'] = [
    'id' => 10000,
    'username' => 'admin',
    'authorize' => '',
    'status' => 1
];

echo "  当前用户: admin\n";
echo "  是否超级管理员: " . (\think\admin\service\AdminService::isSuper() ? '是' : '否') . "\n";

// 强制刷新权限
\think\admin\service\AdminService::apply(true);
echo "  ✓ 已刷新权限\n";

// 3. 获取菜单树
echo "\n【3】调用 MenuService::getTree() 获取菜单\n";

try {
    $menus = \think\admin\service\MenuService::getTree();
    
    echo "  返回的菜单数量: " . count($menus) . "\n\n";
    
    if (empty($menus)) {
        echo "  ❌ 菜单为空！\n";
    } else {
        echo "  菜单内容：\n";
        foreach ($menus as $menu) {
            echo "  ├─ {$menu['title']} (ID:{$menu['id']})\n";
            if (!empty($menu['sub'])) {
                foreach ($menu['sub'] as $sub) {
                    echo "  │  ├─ {$sub['title']} (ID:{$sub['id']})\n";
                    if (!empty($sub['sub'])) {
                        foreach ($sub['sub'] as $subsub) {
                            echo "  │  │  └─ {$subsub['title']} (ID:{$subsub['id']})\n";
                        }
                    }
                }
            }
        }
    }
    
} catch (\Exception $e) {
    echo "  错误: " . $e->getMessage() . "\n";
    echo "  堆栈: " . $e->getTraceAsString() . "\n";
}

// 4. 检查是否有自定义过滤函数
echo "\n【4】检查自定义过滤函数\n";
if (function_exists('admin_menu_filter')) {
    echo "  ⚠️  发现自定义菜单过滤函数 admin_menu_filter\n";
    echo "  这可能会影响菜单显示！\n";
} else {
    echo "  ✓ 没有自定义菜单过滤函数\n";
}

if (function_exists('admin_check_filter')) {
    echo "  ⚠️  发现自定义权限过滤函数 admin_check_filter\n";
} else {
    echo "  ✓ 没有自定义权限过滤函数\n";
}

// 5. 直接测试 MenuService::filter 方法
echo "\n【5】测试菜单过滤逻辑\n";

try {
    // 直接从数据库获取原始菜单
    $rawMenus = \think\admin\model\SystemMenu::mk()
        ->where(['status' => 1])
        ->order('sort desc,id asc')
        ->select()
        ->toArray();
    
    echo "  数据库原始菜单数量: " . count($rawMenus) . "\n";
    
    // 转换为树形结构
    $tree = \think\admin\extend\DataExtend::arr2tree($rawMenus);
    echo "  转换为树形结构后数量: " . count($tree) . "\n";
    
    // 显示树形结构
    echo "\n  树形结构（过滤前）：\n";
    foreach ($tree as $menu) {
        echo "  ├─ {$menu['title']} (ID:{$menu['id']}, URL:{$menu['url']})\n";
        if (!empty($menu['sub'])) {
            echo "     子菜单数量: " . count($menu['sub']) . "\n";
        }
    }
    
    // 使用反射调用私有的 filter 方法
    $reflection = new ReflectionClass(\think\admin\service\MenuService::class);
    $method = $reflection->getMethod('filter');
    $method->setAccessible(true);
    
    $filtered = $method->invoke(null, $tree);
    
    echo "\n  过滤后的菜单数量: " . count($filtered) . "\n";
    echo "\n  过滤后的菜单：\n";
    foreach ($filtered as $menu) {
        echo "  ├─ {$menu['title']} (ID:{$menu['id']})\n";
    }
    
    // 找出被过滤掉的菜单
    $beforeIds = array_column($tree, 'id');
    $afterIds = array_column($filtered, 'id');
    $removedIds = array_diff($beforeIds, $afterIds);
    
    if (!empty($removedIds)) {
        echo "\n  ❌ 被过滤掉的菜单 ID: " . implode(', ', $removedIds) . "\n";
        
        foreach ($tree as $menu) {
            if (in_array($menu['id'], $removedIds)) {
                echo "\n  被过滤菜单详情：\n";
                echo "    标题: {$menu['title']}\n";
                echo "    ID: {$menu['id']}\n";
                echo "    URL: {$menu['url']}\n";
                echo "    NODE: {$menu['node']}\n";
                echo "    子菜单: " . (empty($menu['sub']) ? '无' : count($menu['sub']) . '个') . "\n";
                
                // 分析被过滤的原因
                if (empty($menu['sub']) && (empty($menu['url']) || $menu['url'] === '#')) {
                    echo "    ❌ 原因: 没有子菜单且URL为空或#\n";
                } elseif (!empty($menu['node']) && !\think\admin\service\AdminService::check($menu['node'])) {
                    echo "    ❌ 原因: 权限检查失败 (node: {$menu['node']})\n";
                } else {
                    echo "    ❌ 原因: 未知（需要进一步排查）\n";
                }
            }
        }
    } else {
        echo "\n  ✓ 没有菜单被过滤\n";
    }
    
} catch (\Exception $e) {
    echo "  错误: " . $e->getMessage() . "\n";
}

echo "\n=== 诊断完成 ===\n";

